import { Component, Input, OnInit } from '@angular/core';
import {SFSchema, SFTreeSelectWidgetSchema} from '@delon/form';
import { NzMessageService, NzModalRef } from 'ng-zorro-antd';
import { AreaService } from '../../area.service';
import { _HttpClient } from '@delon/theme';
import { ApiService } from '@core/services/api';
import {delay, map} from "rxjs/operators";


@Component({
  selector: 'app-community-edit',
  templateUrl: './community-edit.component.html',
  styles: []
})
export class CommunityEditComponent implements OnInit {
  @Input()type: number; // 0 新增 1 修改
  @Input()param: any; // 参数
  showForm = false;
  cityList: any;
  typeOption = [
    {label: '社区', value:5},
    {label: '小区（村）', value:6},
    {label: '村组（巷）', value: 7},
  ]
  province = [
    {
      id: '0',
      value: '',
      option: []
    },
    {
      id: '',
      value: '',
      option: []

    },
    {
      id: '',
      value: '',
      option: []

    },
    {
      id: '',
      value: '',
      option: []

    }];
  schema: SFSchema = {
    properties: {
      areaName: {
        type: 'string',
        title: '小区名称',
       // readOnly: this.type == 3,
      },
     /* areaParentId: {
        type: 'string',
        title: '上级区域',
        readOnly: this.type == 3,
        enum: [
        ],
        ui: {
          widget: 'tree-select',
          dropdownStyle: {
            'max-height': '300px'
          },
          expandChange:  (node) => {
            const _node = node.node
            if (_node && _node.children.length === 0 && _node.isExpanded) {
              console.log(_node)
              return this.http.post(this.api.city.tree.url, {id: _node.key}).pipe(map(res => {
                return res.data.map(item => {
                  if (item.cityRank){
                    return {
                      key: item.id,
                      title: item.cityShortName,
                      level: item.cityRank,
                      disabled: item.cityRank < 4
                    }
                  }
                  if (item.areaRank) {
                    return {
                      key: item.id,
                      title: item.areaName,
                      level: item.areaRank,
                    }
                  }
                })
              }))
            }
          }
        },
      },*/
      // areaRank: {
      //   type: 'string',
      //   title:'类型',
      //   enum: [
      //     {label: '社区', value:5},
      //     {label: '小区（村）', value:6},
      //   ]
      // },
      // status: {
      //   type: 'string',
      //   title: '状态',
      //   enum: [
      //     {label: '启用', value: true},
      //     {label: '停用', value: false},
      //   ],
      //   ui: {
      //     widget: 'select',

      //   }
      // },
      areaRemark: {
        type: 'string',
        title: '备注',
      }

    },
    required: ['areaName']
  }
  deleyC(type){
    setTimeout(()=> {
      this.selectChange(type)
    }, 0)
  }
   async selectChange(type: number, id?) {
      switch (type) {
        case 0:
          this.province[0] = {
            id: null,
            value: '',
            option: []
          };
        case 1:
          this.province[1] = {
            id: null,
            value: '',
            option: []
          };
        case 2:
          this.province[2] = {
            id: null,
            value: '',
            option: []
          };
        case 3:
          this.province[3] = {
            id: null,
            value: '',
            option: []
          };
        case 4:
          this.province[4] ={
            id: null,
            value: '',
            option: []
          }
      }
      id =  id==0 ? id : this.province[type-1].id;
      let parentIdList=["0"]
      if(id != 0){
        for(let i=0;i<type;i++){
          parentIdList.push(this.province[i].id)
        }
      }
      if(this.province[1].id == "441900" && type == 3){
        //东莞
        // this.province[4].option = await this.area.getAreaTreeNode(id);
        this.province[type].option = await this.getAreaTreeNode(id,type+1,parentIdList);
      }else{
        // this.province[type].option = await this.area.getAreaTreeNode(id);
        this.province[type].option = await this.getAreaTreeNode(id,type+1,parentIdList);
      }
  }

  getAreaTreeNode(id,rank,parentIdList): Promise<any> {
    return new Promise<any>((resolve, reject) => {
      this.http.post("/core/city/findCityArea", {'id':id,'rank':rank,'parentIdList':parentIdList}).subscribe(res => {
        if (res.data && res.data.length > 0) {
          const node = res.data.map(item => {
            return {
              key: item.id,
              title: item.name,
              level: item.cityRank,
              rank: Number(item.rank),
              parentAllId: item.parentAllId,
              parentId:item.parentId
            }
          })
          resolve(node);

        } else {
          resolve([])
        }
      })
    })
  }
  submit(data: object): void {
    console.log(this.type)
    // if (!this.province[3].id) {
    //   this.msg.warning('请选择所属区域!');
    //   return;
    // }
    const url = this.type == 0 ? this.api.area.add.url : this.api.area.update.url + `/${data['id']}`;
    const method = this.type == 0 ? this.api.area.add.method : this.api.area.update.method;
    console.log(this.province)
   
    if(this.province[3].id == null){
      //等于null表示没有街道
      data['areaParentId'] = this.province[2].id;
      data['cityId'] = this.province[2].id;
      data['areaParentAllId'] = `${this.province[0].id},${this.province[1].id},${this.province[2].id},${this.province[2].id}`;
    }else{
      //有街道数据
      data['areaParentId'] = this.province[3].id;
      data['cityId'] = this.province[3].id;
      data['areaParentAllId'] = `${this.province[0].id},${this.province[1].id},${this.province[2].id},${this.province[3].id}`;
    }
    if (this.province[4].id) {
      delete data['cityId'];
      data['areaParentAllId'] += ',' + this.province[4].id;
      data['areaParentId'] = this.province[4].id;
      if (data['areaRank'] == 5) {
        this.msg.warning('社区下不可添加社区！');
        return;
      }
    }
    delete data['createTime'];
    delete data['updateTime'];
    delete data['_values'];
    console.log(data);
    data['status'] = true
    data['areaRank'] = 6
    this.http.request<any>(method, url , {body:data}).subscribe(res => {
      if (res.status === '201'|| res.status === '200') {
        this.msg.success(res.message);
        this.modalRef.triggerOk();
      } else {
        this.msg.error(res.message)
      }
    })
  }
  loadNode(data): Promise <any>{
    return this.area.getAreaTreeNode(data.key)
  }
  constructor(
    private msg: NzMessageService,
    private modalRef: NzModalRef,
    private area: AreaService,
    private http: _HttpClient,
    private api: ApiService
  ) { }
  async ngOnInit() {
    console.log(this.param)
    this.selectChange(0, 0)

    if (this.type) {
      const idArr = this.param.areaParentAllId.split(',');
      for (let i = 0 ; i < 5; i++) {
        this.province[i].id = idArr[i];
        if (i < 4) {
          const id = i + 1;
          await this.selectChange(id)
        }
      }
    }
    this.showForm = true;
    /*this.area.getAreaTreeNode(0).then(
      res => {
        this.schema.properties.areaParentId.enum = res.map(item => {
                item.disabled = true;
          return item
        });
        if (this.param.areaParentName) {
          this.schema.properties.areaParentId.ui['placeholder'] = this.param.areaParentName;
        }
        this.showForm = true;
      }
    )*/
    /*this.area.getCityList().subscribe(res => {
      if (res.status == '200') {
        this.cityList = res.data.map(item => {
          return {value: item.id, label: item.cityName}
        })
      }
      this.schema.properties.cityId.enum = this.cityList;
      this.showForm = true;
    })*/
  }

}
